// extract module
var connect = require('connect');
var fs = require('fs');
var ejs = require('ejs');

var counter = 0;
function Product(name, image, price, count) {
	this.index = counter++;
	this.name = name;
	this.image = image;
	this.price = price;
	this.count = count;
};

var products = [
    new Product('JavaScript', 'chrome.png', 28000, 30),
    new Product('JQuery', 'chrome.png', 28000, 30),
    new Product('Node.js', 'chrome.png', 32000, 30),
    new Product('Socket.io', 'chrome.png', 17000, 30),
    new Product('Connect', 'chrome.png', 18000, 30),
    new Product('Express', 'chrome.png', 31000, 30),
    new Product('EJS', 'chrome.png', 12000, 30)
];

// create web server
var server = connect.createServer();
server.use(connect.static(__dirname + '/resources'));
server.use(connect.router(function(app) {
	// read html file
	var html = fs.readFileSync('./resources/shopping.html', 'utf8');
	
	app.get('/', function(request, response) {
		response.writeHead(200, {'Content-Type': 'text/html'});
		response.end(ejs.render(html, {
			products: products
		}));
	});
}));

// run web server
server.listen(52273, function() {
	console.log('Server running at http://localhost:52273');
});

// create and run socket server
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
	var cart = {};
	
	function onReturn(index) {
		products[index].count++;
		
		clearTimeout(cart[index].timerId);
		
		delete cart[index];
		
		io.sockets.emit('count', {
			index: index,
			count: products[index].count
		});
	};
	
	// cart event
	socket.on('cart', function(index) {
		products[index].count--;
		
		cart[index] = {};
		cart[index].index = index;
		cart[index].timerId = setTimeout(function() {
			onReturn(index);
		}, 1000 * 60 * 10);
		
		// emit count event
		io.sockets.emit('count', {
			index: index,
			count: products[index].count
		});
	});
	
	// buy event
	socket.on('buy', function(index) {
		// clar timer
		clearTimeout(cart[index].timerId);
		
		delete cart[index];
		
		io.sockets.emit('count', {
			index: index,
			count: products[index].count
		});
	});
	
	socket.on('return', function(index) {
		onReturn(index);
	});
});